﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Xml;
using System.Threading;

namespace DownloadAlbumMp3Zing
{
    public partial class Form1 : Form
    {
        String linkAlbum = null;
        string pathSaveLink = null;
        string pathSaveMusic = null;
        string tenbaihat;
        public Form1()
        {
            InitializeComponent();
        }

        private void InfoAlbum()
        {
            if (linkAlbum == null) return;
            //load du lieu html
            HtmlAgilityPack.HtmlDocument document = GetDocument(linkAlbum);

            if (document == null) return;
            //get node chua danh sach va client
            HtmlNode nodes = document.DocumentNode.SelectSingleNode("//ul[@class='playlist']");
            if (nodes != null)
            {
                //lay thong tin tung bai hat
                foreach (HtmlNode node in nodes.ChildNodes)
                {
                    if (node.Name == "li")
                    {
                        //show ten bai hat
                        //System.Threading.Thread.Sleep(3000);
                        ShowAndSaveBaiHat(node);
                    }
                }
            }
        }

        private void ShowAndSaveBaiHat(HtmlNode node)
        {
            /*cau truc
                <li id="songZW7IWC6U" class="fn-playlist-item fn-song fn-current pause" data-order="01" data-type="song" data-id="ZW7IWC6U" data-code="ZHxHtZHsQdHWzAStZbxTbHLH" data-active="show-tool">                         
                    <div class="item-song">                             
                        <span>01</span>                             
                        <h3>
                            <a class="fn-name" data-order="01" href="http://mp3.zing.vn/bai-hat/Kick-The-Dust-Up-Luke-Bryan/ZW7IWC6U.html" title="Kick The Dust Up - Luke Bryan">Kick The Dust Up</a>
                        </h3>                             

                    </div>                     
                </li>

            */
            HtmlNode node1 = node.ChildNodes[1];//div[class="item-song"]
            if (node1 != null)
            {
                HtmlNode node2 = node1.ChildNodes[3];//get h3 tag
                if (node2 != null)
                {
                    HtmlNode node3 = node2.ChildNodes[0]; //get a tag
                    if (node3 != null)
                    {
                        lsbDanhsach.Items.Add(node3.Attributes["title"].Value);
                        SaveLinkBaihat(node3.Attributes["href"].Value, node3.Attributes["title"].Value);
                    }
                }

            }
        }

        private void SaveLinkBaihat(string linkbaihat, string tenbaihat)
        {

            //save link download
            using (StreamWriter writer = File.AppendText(pathSaveLink))
            {
                writer.WriteLine(tenbaihat + " | " + linkbaihat);
            }
        }

        private string GetLinkDownload(string linkbaihat)
        {
            HtmlAgilityPack.HtmlDocument document = GetDocument(linkbaihat);

            if (document == null) return null;
            //get tag chua dia chi xml
            HtmlNode n = document.DocumentNode.SelectSingleNode("//div[@id='player5']");
            if (n != null)
            {
                string xmlUrl = n.Attributes["data-xml"].Value;

                //tra ve link down load bai hat
                StreamReader reader = new StreamReader(new GZipStream(WebRequest.Create(xmlUrl).GetResponse().GetResponseStream(), CompressionMode.Decompress));
                XmlDocument xml = new XmlDocument();
                xml.Load(reader);
                XmlNodeList nodes = xml.DocumentElement.ChildNodes;
                foreach (XmlNode node in nodes)
                {
                    foreach (XmlNode nodechild in node.ChildNodes)
                    {
                        if (nodechild.Name.Equals("source"))
                        {
                            return nodechild.InnerText;
                        }
                    }
                }
            }
            return null;
        }

        private HtmlAgilityPack.HtmlDocument GetDocument(string link)
        {
            if (link == null || link == "") return null;
            //lay du lieu tu trang web va giai nen
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
            request.ReadWriteTimeout = 5000;
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            try
            {
                using (WebResponse rs = request.GetResponse())
                using (Stream stream = rs.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress));
                    document.Load(reader);
                    reader.Close();
                }
                return document;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao", MessageBoxButtons.OK);
            }
            return null;
        }

        private void btnsearch_Click(object sender, EventArgs e)
        {
            linkAlbum = txtSearch.Text;

            pathSaveLink = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\link.txt";
            if (File.Exists(pathSaveLink))
            {
                File.Delete(pathSaveLink);
            }
            pathSaveMusic = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            InfoAlbum();
        }

        private void lsbDanhsach_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tenbaihat = lsbDanhsach.SelectedItem.ToString();

            //tim link bai hat trong file da luu
            using (StreamReader read = new StreamReader(pathSaveLink))
            {
                string line = null;
                while ((line = read.ReadLine()) != null)
                {
                    if (line.Contains(tenbaihat))
                        break;
                }
                if (line != null)
                {
                    //get link download
                    string linkdownload = GetLinkDownload(line.Substring(line.IndexOf("|") + 1));
                    media.URL = linkdownload;
                }

            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (this.backgroundWorker1.IsBusy)
                MessageBox.Show("Dang download ban vui long cho!", "Thong bao", MessageBoxButtons.OK);
            else
            {
                this.backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //lấy kích thước file download
            Uri url = new Uri(media.URL);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Close();
            Int64 filesize = response.ContentLength;
            //tổng số byte đã download được
            Int64 soByteDownloaded = 0;

            using (WebClient client = new WebClient())
            {
                using (Stream streamRemote = client.OpenRead(url))
                {
                    using (Stream streamlocal = new FileStream(pathSaveMusic + "\\" + tenbaihat + ".mp3", FileMode.Create))
                    {
                        int iByteSize = 0;
                        byte[] byteBuffer = new byte[filesize];
                        while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                        {
                            //viết số byte đã dowwnload được  vào file lưu trữ
                            streamlocal.Write(byteBuffer, 0, iByteSize);
                            soByteDownloaded += iByteSize;

                            //tính toán  phần trăm progressBar
                            double dIndex = (double)(soByteDownloaded);
                            double dTotal = (double)byteBuffer.Length;
                            double dProgressPercentage = (dIndex / dTotal);
                            int iProgressPercentage = (int)(dProgressPercentage * 100);

                            //update progressbar
                            backgroundWorker1.ReportProgress(iProgressPercentage);
                        }
                        streamlocal.Close();
                    }
                    streamRemote.Close();
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int dodai = lsbDanhsach.Bounds.Right - lsbDanhsach.Bounds.Left;

            int x2 = e.ProgressPercentage * (dodai / 100);

            Graphics dohoa = this.CreateGraphics();
            dohoa.DrawLine(new Pen(Color.Blue, 5), new Point(lsbDanhsach.Bounds.Left, lsbDanhsach.Bounds.Bottom),
                new Point(x2, lsbDanhsach.Bounds.Bottom));
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Graphics dohoa = this.CreateGraphics();
            dohoa.DrawLine(new Pen(this.BackColor, 5), new Point(lsbDanhsach.Bounds.Left, lsbDanhsach.Bounds.Bottom),
                new Point(lsbDanhsach.Bounds.Right, lsbDanhsach.Bounds.Bottom));
        }
    }
}
